package com.yksj.healthtalk.ui.interestwall;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshMultiColumnListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.staggered.lib.MultiColumnListView;
import org.staggered.lib.internal.StaggerAdapterView;
import org.staggered.lib.internal.StaggerAdapterView.OnItemClickListener;
import org.universalimageloader.core.DefaultConfigurationFactory;
import org.universalimageloader.core.DisplayImageOptions;
import org.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.yksj.healthtalk.entity.InterestWallEntity;
import com.yksj.healthtalk.entity.TagEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 瀑布流fragment
 * 
 * @author jack_tang
 */
public class WaterFallFragment extends Fragment implements OnItemClickListener,
		OnClickListener, OnRefreshListener<MultiColumnListView>,
		OnLastItemVisibleListener {
	public static final String TAG = "WaterFallFragment";
	public static final int DELETE_REQUEST_CODE = 0x00000002;
	public static final String DEFAULT_PIC_ID = "0";
	public static final String COLLECT_STORAGE = "collect_store";
	// 用户发布兴趣墙
	public static final int USER_RELEASE_WATERFALL = 2;
	// 所有图片
	public static final int INTERESTWALL_WATERFALL = 1;
	private PullToRefreshMultiColumnListView mListView;
	private int mColumnNumber = 2;
	private float mWidthSize;// 每个图片的宽度

	private ImageLoader mImageLoader;
	private DisplayImageOptions mDisplayImageOptions;
	private ImageAdapter mAdapter;
	private int position = -1;// 处于viewpager内的位置
	private int tag = -1;// tag标志位 1-兴趣墙主程序 2-我发布我收藏
	private String classId; // super //大类id
	private String secondaryId;// id小类id
	private String picId;// 最后一张图片的id
	private String type;// 类型标志位
	private int pageCount = 1;
	private final String pageNum = "30";
	private List<InterestWallEntity> imageWallData = new ArrayList<InterestWallEntity>();

	/**
	 * 主界面瀑布流对象
	 * 
	 * @param position
	 * @param tag
	 *            tag标志位 1-兴趣墙主程序 2-我发布我收藏
	 * @param classId
	 *            大类id
	 * @param secondaryId
	 *            小类id
	 * @return
	 */
	public static WaterFallFragment newInstance(int position, int tag,
			String classId, String secondaryId) {
		WaterFallFragment f = new WaterFallFragment();
		Bundle mBundle = new Bundle();
		mBundle.putInt("position", position);
		mBundle.putInt("tag", tag);
		mBundle.putString("classId", classId);
		mBundle.putString("secondaryId", secondaryId);
		f.setArguments(mBundle);
		return f;
	}

	public static WaterFallFragment newInstance(int position, int tag,
			String classId, String secondaryId, String type) {
		WaterFallFragment f = new WaterFallFragment();
		Bundle mBundle = new Bundle();
		mBundle.putInt("position", position);
		mBundle.putInt("tag", tag);
		mBundle.putString("classId", classId);
		mBundle.putString("secondaryId", secondaryId);
		mBundle.putString("type", type);
		f.setArguments(mBundle);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mImageLoader = ImageLoader.getInstance();
		mDisplayImageOptions = DefaultConfigurationFactory
				.createGalleryDisplayImageOptions(getActivity());
		this.type = getArguments().getString("type");
		if (savedInstanceState != null && tag == INTERESTWALL_WATERFALL) {
			this.classId = this.getArguments().getString("classId");
			this.secondaryId = this.getArguments().getString("secondaryId");
			if (this.classId.equals(savedInstanceState.getString("classId"))
					&& this.secondaryId.equals(savedInstanceState
							.getString("secondaryId"))) {
				this.tag = savedInstanceState.getInt("tag");
				this.position = savedInstanceState.getInt("position");
			} else {
				this.tag = this.getArguments().getInt("tag");
				this.position = this.getArguments().getInt("position");
			}
		} else {
			this.classId = this.getArguments().getString("classId");
			this.secondaryId = this.getArguments().getString("secondaryId");
			this.tag = this.getArguments().getInt("tag");
			this.position = this.getArguments().getInt("position");
		}
	}

	public void initData() {
		DisplayMetrics metrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		mWidthSize = metrics.widthPixels / mColumnNumber;
		if (tag == INTERESTWALL_WATERFALL) {
			switch (position) {
			case 3:// 全部
				queryInterestWallDefaultContent(4, classId, secondaryId,
						DEFAULT_PIC_ID);
				break;
			case 2:// 最新
				queryInterestWallDefaultContent(1, classId, secondaryId,
						DEFAULT_PIC_ID);
				break;
			case 0:// 最热
				queryInterestWallDefaultContent(2, classId, secondaryId,
						DEFAULT_PIC_ID);
				break;
			case 1:// 推荐
				queryInterestWallDefaultContent(3, classId, secondaryId,
						DEFAULT_PIC_ID);
				break;
			}
		} else if (tag == USER_RELEASE_WATERFALL) {
			switch (position) {
			case 0:// 已发布
				queryInterestWallUserReleaseContent(position + 1, 1, pageNum);
				break;
			case 1:// 已收藏
				queryInterestWallUserReleaseContent(position + 1, 1, pageNum);
				break;
			}
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.waterfall_layout, container,
				false);
		mListView = (PullToRefreshMultiColumnListView) view
				.findViewById(android.R.id.list);
		mListView.setMode(Mode.PULL_FROM_END);
		mListView.setOnRefreshListener(this);
		mListView.setOnLastItemVisibleListener(this);
		MultiColumnListView refreshableView = mListView.getRefreshableView();
		mColumnNumber = refreshableView.getColumnNumber();
		mAdapter = new ImageAdapter(this.getActivity());
		mListView.setAdapter(mAdapter);
		refreshableView.setOnItemClickListener(this);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		boolean containsKey = getArguments().containsKey("entity");
		if (containsKey) {
			onDataChangeByType((TagEntity) getArguments().getParcelable(
					"entity"));
		} else {
			initData();
		}
	}

	public void onChangeSeachName() {
		onDataChangeByType((TagEntity) getArguments().getParcelable("entity"));
	}

	private void onShowToast(String str) {
		if (isDetached() || isRemoving() || isHidden()) {
			ToastUtil.showShort(getActivity(), str);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (tag == INTERESTWALL_WATERFALL) {
			outState.putString("classId", classId);
			outState.putString("secondaryId", secondaryId);
			outState.putInt("position", position);
			outState.putInt("tag", tag);
		}
	}

	@Override
	public void onItemClick(StaggerAdapterView<?> parent, View view,
			int position, long id) {
		Intent intent = new Intent(this.getActivity(),
				InterestContentActivity.class);
		intent.putExtra("tag", tag);
		intent.putExtra("picid", id + "");
		intent.putExtra("position", this.position);
		startActivityForResult(intent, DELETE_REQUEST_CODE);
	}

	/**
	 * @author crj 瀑布流适配器
	 */
	class ImageAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private List<InterestWallEntity> adapterMetaData;

		public ImageAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			adapterMetaData = new ArrayList<InterestWallEntity>();
		}

		@Override
		public int getCount() {
			return adapterMetaData.size();
		}

		@Override
		public Object getItem(int arg0) {
			return adapterMetaData.get(arg0).getImageUrl();
		}

		@Override
		public long getItemId(int arg0) {
			InterestWallEntity entity = adapterMetaData.get(arg0);
			return Long.parseLong(entity.getId());
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			final InterestWallEntity entity = adapterMetaData.get(arg0);
			String url = entity.getImageUrl();
			final ImageHolder holder;
			if (convertView == null) {
				holder = new ImageHolder();
				convertView = mInflater.inflate(R.layout.waterfall_item, arg2,
						false);
				holder.mImageView = (ImageView) convertView
						.findViewById(R.id.waterfall_imageView);
				holder.isShopUrl = (ImageView) convertView
						.findViewById(R.id.is_shop_url);
				holder.mTextView = (TextView) convertView
						.findViewById(R.id.waterfall_textView);
				convertView.setTag(holder);
			} else {
				holder = (ImageHolder) convertView.getTag();
			}
			android.view.ViewGroup.LayoutParams layoutParams = convertView
					.getLayoutParams();
			layoutParams.width = entity.getPicWidth();
			layoutParams.height = entity.getPicHeight();

			mImageLoader.displayImage(url, holder.mImageView,
					mDisplayImageOptions);
			String str = entity.getImageState();// 审核状态
			if (!TextUtils.isEmpty(str)) {
				holder.mTextView.setVisibility(View.VISIBLE);
				if ("10".equals(str)) {
					holder.mTextView.setText("审核中...");
					holder.mTextView.setTextColor(Color.WHITE);
				} else if ("30".equals(str)) {
					holder.mTextView.setText("审核失败");
					holder.mTextView.setTextColor(getResources().getColor(
							R.color.orange));
				} else if ("20".equals(str)) {
					holder.mTextView.setVisibility(View.INVISIBLE);
				}
			}
			// 是否有url
			if (TextUtils.isEmpty(entity.getPictureUrl())) {
				holder.isShopUrl.setVisibility(View.GONE);
			} else {
				holder.isShopUrl.setVisibility(View.VISIBLE);
			}
			return convertView;
		}
	}

	static class ImageHolder {
		ImageView isShopUrl;
		ImageView mImageView;
		TextView mTextView;
	}

	public void notifyDataChanged() {
		if (mAdapter != null) {
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onClick(View v) {
		if (tag == 1) {
			if (imageWallData.size() > 0) {
				picId = ((InterestWallEntity) imageWallData.get(imageWallData
						.size() - 1)).getId();
			}
			switch (position) {
			case 0:
				queryInterestWallDefaultContent(2, classId, secondaryId, picId);
				break;
			case 1:
				queryInterestWallDefaultContent(3, classId, secondaryId, picId);
				break;
			case 2:
				queryInterestWallDefaultContent(1, classId, secondaryId, picId);
				break;
			case 3:
				queryInterestWallDefaultContent(4, classId, secondaryId, picId);
				break;
			}
		} else {
			queryInterestWallUserReleaseContent(position + 1, pageCount,
					pageNum);
		}
	}

	/**
	 * 操作指定图片，删除或取消收藏
	 * 
	 * @param picid
	 */
	public void refreshData(int picid) {
		for (int i = 0; i < imageWallData.size(); i++) {
			if ((picid + "").equals(imageWallData.get(i).getId())) {
				imageWallData.remove(i);
				mAdapter.notifyDataSetChanged();
			}
		}
	}

	/**
	 * 刷新所有数据
	 */
	public void refreshAllData(int position) {
		if (imageWallData != null)
			imageWallData.clear();
		else {
			imageWallData = new ArrayList<InterestWallEntity>();
		}
		queryInterestWallUserReleaseContent(position + 1, 1, pageNum);
	}

	public void clearData() {
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onResume() {
		super.onResume();
		if (tag == USER_RELEASE_WATERFALL)
			queryInterestWallUserReleaseContent(position + 1, 1, pageNum);
	}

	/*********************************************************
	 * 网络请求
	 *********************************************************/

	// private ObjectHttpResponseHandler handler;
	/**
	 * Tag 为1时 表示所有图片的图片墙。 加载默认情况下图片信息
	 * 
	 * @param position2
	 *            表示需要传递参数 排序类型如果是4，表示全部。1表示最新。2表示最热。3表示推荐
	 * @param secondaryId
	 *            小类id
	 * @param infoId
	 *            大类id， 暂时小类id唯一， 所以不需要直接大类id
	 * @param picid
	 *            上次刷新的最后一个图片id，回传到服务器，服务器会根据这个图片找到改图片在数据库排序内后面的图片
	 */
	private void queryInterestWallDefaultContent(int position2,
			final String classId, final String secondaryId, final String picid) {
		HttpRestClient.doHttpQueryInterestWall("1", classId, secondaryId, "1",
				pageNum, position2 + "", picid + "", type,
				new ObjectHttpResponseHandler() {
					@Override
					public Object onParseResponse(String content) {
						if ("N".equals(content)) {
							return null;
						} else {
							return onParseData(content, picid);
						}
					}

					@Override
					public void onSuccess(int statusCode, Object response) {
						if (response != null) {
							onResponseDataSucceed(response);
						}
					}

					@Override
					public void onStart() {
						super.onStart();
						mListView.setRefreshing();
					}

					@Override
					public void onFinish() {
						super.onFinish();
						mListView.onRefreshComplete();
					}
				});
	}

	/**
	 * 返回json数据解析（非ui线程）
	 * 
	 * @param content
	 * @param id
	 * @return
	 */
	private List<InterestWallEntity> onParseData(String content, String id) {
		List<InterestWallEntity> data = new ArrayList<InterestWallEntity>();
		try {
			JSONObject jsonObject = new JSONObject(content);
			if (jsonObject.has("maxId")) {// 拿到兴趣墙的最大id
				int maxId = jsonObject.getInt("maxId");
				if (Integer.valueOf(SharePreUtils.fatchInterestWallId()) < maxId) {
					SharePreUtils.savInterestWallId(String.valueOf(maxId));
				}
			}
			// 兴趣墙数据
			JSONArray groupJsonArray = jsonObject.getJSONArray("group");
			for (int i = 0; i < groupJsonArray.length(); i++) {
				JSONObject tempJson = groupJsonArray.getJSONObject(i);
				InterestWallEntity entity = DataParseUtil
						.parseWallEntity(tempJson);
				float scale = mWidthSize / entity.getPicWidth();
				entity.setPicWidth((int) (entity.getPicWidth() * scale));
				entity.setPicHeight((int) (entity.getPicHeight() * scale));
				data.add(entity);
			}
			return data;
		} catch (JSONException e) {
		}
		return null;
	}

	/**
	 * ui线程 返回数据解析
	 * 
	 * @param object
	 */
	private void onResponseDataSucceed(Object object) {
		if (object != null) {
			List<InterestWallEntity> tempData = (List<InterestWallEntity>) object;
			imageWallData.addAll(tempData);
			mAdapter.adapterMetaData.addAll(tempData);
			mAdapter.notifyDataSetChanged();
			if (tempData.size() <= 0
					|| tempData.size() < Integer.valueOf(pageNum)) {
				onShowToast("没有更多的图片");
			} else {
			}
		} else {
			onShowToast("没有更多的图片");
		}
	}

	/**
	 * 请求我发布与我收藏内容方法。
	 * 
	 * @param flag
	 *            1-我发布 2-我收藏
	 */
	private void queryInterestWallUserReleaseContent(final int flag,
			final int pageNum, final String pageSize) {
		HttpRestClient.doHttpQueryInterestWallUserRelease("0", "0", pageNum
				+ "", pageSize, SmartFoxClient.getLoginUserId(), flag + "",
				new ObjectHttpResponseHandler(getActivity()) {
					@Override
					public Object onParseResponse(String content) {
						List<InterestWallEntity> entities = JsonParseUtils
								.parseInterestUserEntity(content, mWidthSize);
						return entities;
					}

					@Override
					public void onSuccess(int statusCode, Object response) {
						if (response != null) {
							// 如果也好是1 代表数据为重新加载 要清理原来的数据
							if (pageNum == 1)
								imageWallData.clear();
							List<InterestWallEntity> list = (List<InterestWallEntity>) response;
							imageWallData.addAll(list);
							if (flag == 2) {
								// 如果进入我收藏界面则把所有已收藏的数据写入手机内存
								List<String> collect = new ArrayList<String>();
								for (int i = 0; i < list.size(); i++) {
									collect.add(list.get(i).getId());
								}
							}
							mAdapter.adapterMetaData = imageWallData;
							mAdapter.notifyDataSetChanged();
							// 如果获取的数据量少于 应该得到的数据量 表示没有更多的了。隐藏加载更多
							if (list.size() < Integer.parseInt(pageSize)) {
								// dismissFooter();
								pageCount++;
							}
						}
					}
				});
	}

	/**
	 * 通过调节过滤
	 * 
	 * @param str
	 */
	public void onDataChangeByType(TagEntity str) {
		String id = str.getId();
		if (id.equals("Name")) {// 按名称搜索
			HttpRestClient.doHttpInterestWallByCondition(str.getName(), "1",
					"1", pageNum, new ObjectHttpResponseHandler(getActivity()) {
						@Override
						public Object onParseResponse(String cotent) {
							return onParseData(cotent, null);
						}

						@Override
						public void onSuccess(Object response) {
							List<InterestWallEntity> list = (List<InterestWallEntity>) (response);
							if (list.size() < Integer.valueOf(pageNum))
								// dismissFooter();
								if (mAdapter != null) {
									mAdapter.adapterMetaData = list;
									mAdapter.notifyDataSetChanged();
								}
						}
					});
		} else {
			this.classId = str.getUpperId();
			this.secondaryId = str.getId();
			this.pageCount = 1;
			if (mAdapter != null) {
				mAdapter.adapterMetaData.clear();
				mAdapter.notifyDataSetChanged();
			}
			initData();
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		refreshView.onRefreshComplete();
	}

	@Override
	public void onLastItemVisible() {
		if (tag == 1) {
			if (imageWallData.size() > 0) {
				picId = ((InterestWallEntity) imageWallData.get(imageWallData
						.size() - 1)).getId();
			}
			switch (position) {
			case 0:
				queryInterestWallDefaultContent(2, classId, secondaryId, picId);
				break;
			case 1:
				queryInterestWallDefaultContent(3, classId, secondaryId, picId);
				break;
			case 2:
				queryInterestWallDefaultContent(1, classId, secondaryId, picId);
				break;
			case 3:
				queryInterestWallDefaultContent(4, classId, secondaryId, picId);
				break;
			}
		} else {
			queryInterestWallUserReleaseContent(position + 1, pageCount,
					pageNum);
		}
	}
}
